package scfg.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import scfg.output.Display;
import scfg.output.RNAFormattedFile;
import desposito6.utils.CommandLine;

public class AmbiguousChecker {

	public static Display output;

	static {
		output = new Display("AmbiguousChecker");
	}

	private static boolean processFile(File f) {
		output.out("Processing " + f.getName() + "...\t");
		RNAFormattedFile rnaFile = new RNAFormattedFile(f.getAbsolutePath());
		rnaFile.parseRNAFormattedFile(f.getAbsolutePath());
		String seq = rnaFile.get("seq");
		if(!seq.toUpperCase().matches("[ACGU]+")){
			output.out("\t" + seq.indexOf('N') + "\t" + seq.replaceAll("[GCAU]+", ""));
		}
		return seq == null ? false : !seq.toUpperCase().matches("[ACGU]+");
	}

	public static List<String> processDir(File base, List<String> ambiguousFiles) {
		output.out("Openning " + base.getName());

		if (!base.exists()) {
			output.eout("Base Directory directory does not extist:\n\t"
					+ base.getAbsolutePath());
			return null;
		}
		File[] files = base.listFiles();
		for (File f : files) {
			if (f.getName().endsWith(".rna"))
				if (processFile(f))
					ambiguousFiles.add(f.getAbsolutePath());
			if (f.isDirectory())
				processDir(f, ambiguousFiles);
		}
		return ambiguousFiles;
	}

	public static void ambiguousMover(List<String> ambiguousFiles,
			String destDir) {
		if (ambiguousFiles == null) {
			return;
		}
		int count = 0;
		File destDirFile = new File(destDir);
		if (!destDirFile.exists())
			destDirFile.mkdir();
		try {
			for (String filename : ambiguousFiles) {
				File orig = new File(filename);
				if (filename.endsWith(".rna") && orig.exists()) {
					String dest = destDir + "/" + orig.getName();
					Process p = Runtime.getRuntime().exec(
							new String[] { "/bin/sh", "-c",
									"cp " + filename + " " + dest });
					p.waitFor();
					if (!(new File(dest).exists())) {
						output.out("\tERROR: " + filename);
					}
				} else
					output.out((count++) + "\tSKIPPING: " + filename);
			}
		} catch (IOException e) {
		} catch (InterruptedException e) {
		}
	}

	public static void ambiguousDeleter(List<String> ambiguousFiles) {
		if (ambiguousFiles == null) {
			return;
		}
		int count = 0;
		try {
			for (String filename : ambiguousFiles) {
				File orig = new File(filename);
				if (filename.endsWith(".rna") && orig.exists()) {
					Process p = Runtime.getRuntime().exec(
							new String[] { "/bin/sh", "-c", "rm " + filename });
					p.waitFor();
					if (new File(filename).exists())
						output.out("\tERROR: " + filename);
				} else
					output.out((count++) + "\tSKIPPING: " + filename);
			}
		} catch (IOException e) {
		} catch (InterruptedException e) {
		}
	}

	public static String helpMessage() {
		return "\n[scfg.utils.StructureAggregator]\n\t"
				+ "* -h Display help message.\n\t" + "* -s Source folder.\n\t"
				+ "* -d Destination folder - Copy. (Optional)\n\t"
				+ "* -delete Delete ambiguous files. (Optional)"
				+ "* -o Output filename. (Optional)\n\t"
				+ "* -c Generate compressed file. (Optional)"
				+ "* -v Display verbose output. (Optional)\n\n";
	}

	/**
	 * <pre>
	 * -h Display help message.
	 * -s Source folder.
	 * -d Destination folder - Copy. (Optional)
	 * -delete Delete ambiguous files. (Optional)
	 * -o Output filename. (Optional)
	 * -c Generate compressed files. (Optional)
	 * -v Display verbose output. (Optional)
	 * </pre>
	 * 
	 * -s /home/david/Documents/REU/RNA/rna_files/ -d
	 * /home/david/Documents/REU/RNA/ambiguous_files/ -v -delete
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		if (CommandLine.containsArg(args, "-h") >= 0) {
			output.out(helpMessage());
			output.finalizeDisplay();
			return;
		}
		int temp = CommandLine.containsArg(args, "-o");
		if (temp >= 0 && temp < args.length - 1) {
			output = new Display(args[temp + 1], args[temp + 1] + "_error.log",
					true);
		}
		temp = CommandLine.containsArg(args, "-s");
		String sourceName = null;
		if (temp >= 0 && temp < args.length - 1) {
			sourceName = args[temp + 1];
		}
		temp = CommandLine.containsArg(args, "-d");
		String destinationName = null;
		if (temp >= 0 && temp < args.length - 1) {
			destinationName = args[temp + 1];
		} else {
			destinationName = ".ambiguous_rna/";
		}
		output.setVerbose(CommandLine.containsArg(args, "-v") >= 0);
		File srcFile = new File(sourceName);
		List<String> ambiguousFiles = processDir(srcFile,
				new ArrayList<String>());
		if (destinationName != null)
			ambiguousMover(ambiguousFiles, destinationName);
		if (CommandLine.containsArg(args, "-delete") >= 0)
			ambiguousDeleter(ambiguousFiles);
		output.out("\n\n\n\t[EXITING StructureAggregator.main]");
		output.finalizeDisplay();
	}
}
